package com.friddle.util.Function;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by friddle on 15-2-11.
 */
public class UrlFunction {
	public static Logger logger = LoggerFactory.getLogger(UrlFunction.class);
	public static String getHostFromUrl(String url) {
		URL newurl = null;
		if (url!=null&&!url.startsWith("http://")) {
			url = "http://" + url;
		}
		try {
			newurl = new URL(url);
			return newurl.getHost();
		} catch (MalformedURLException e) {
			logger.error("url:" + url);
			logger.error("exception", e);
		}
		return null;
	}

	public static String GetLastUrl(String url) {
		String[] strs = url.split("/");
		return strs[strs.length - 1];
	}

	public static String getLastItemFromUrl(String url) {
		try {
			url = url.substring(url.lastIndexOf("/") + 1, url.length());
			return url;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getClearUrlFromUrl(String url) {
		if (!url.startsWith("http://")) {
			url = "http://" + url;
		}
		URL newurl = null;
		try {
			newurl = new URL(url);
			return newurl.getPath();
		} catch (MalformedURLException e) {
			logger.error("url:" + url);
			logger.error("exception", e);
		}
		return null;
	}

	public static String getRidOfHttp(String http) {
		if (http == null) {
			return http;
		}
		if (http.startsWith("http://")) {
			http = http.replaceAll("http://", "");
		}
		return http;
	}

}
